﻿using System;
using Microsoft.Practices.ObjectBuilder;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.Practices.Web.UI.WebControls;

namespace Locator.Products.Views
{
    public partial class ProductSearch : Microsoft.Practices.CompositeWeb.Web.UI.UserControl, IProductSearchView
    {
        private ProductSearchPresenter presenter;

        public int SearchResultCount { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.presenter.OnViewInitialized();
            }

            this.presenter.OnViewLoaded();
        }

        [CreateNew]
        public ProductSearchPresenter Presenter
        {
            get
            {
                return this.presenter;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                this.presenter = value;
                this.presenter.View = this;
            }
        }

        protected void ButtonSearchByProductName_Click(object sender, EventArgs e)
        {
            this.presenter.OnSearchByProductNameClicked();
        }

        protected void ProductsDataSource_Updated(object sender, ObjectContainerDataSourceStatusEventArgs e)
        {
            this.presenter.OnProductAddedForUser((Locator.Products.UserProduct)e.Instance);
        }

        public string ProductNameToSearch
        {
            get { return this.TextBoxProductName.Text; }
        }

        // TODO: Forward events to the presenter and show state to the user.
        // For examples of this, see the View-Presenter (with Application Controller) QuickStart:
        //	

        public void SetSearchResults(List<UserProduct> list)
        {
            this.ProductsDataSource.DataSource = list;
        }

        protected void ListViewProducts_DataBound(object sender, EventArgs e)
        {
            var labelCount = this.ListViewProducts.FindControl("LabelCount") as Label;
            if (labelCount != null)
                labelCount.Text = this.ListViewProducts.Items.Count.ToString();
        }
    }
}

